import os
import gzip
import struct
import numpy as np

from paddle.fluid.io import Dataset
from helm.datasets.utils import _check_exists_and_download

__all__ = ["MNIST"]

URL_PREFIX = 'https://dataset.bj.bcebos.com/mnist/'

TEST_IMAGE_FILENAME = 't10k-images-idx3-ubyte.gz'
TEST_IMAGE_URL = URL_PREFIX + TEST_IMAGE_FILENAME
TEST_IMAGE_MD5 = '9fb629c4189551a2d022fa330f9573f3'

TEST_LABEL_FILENAME = 't10k-labels-idx1-ubyte.gz'
TEST_LABEL_URL = URL_PREFIX + TEST_LABEL_FILENAME
TEST_LABEL_MD5 = 'ec29112dd5afa0611ce80d1b7f02629c'

TRAIN_IMAGE_FILENAME = 'train-images-idx3-ubyte.gz'
TRAIN_IMAGE_URL = URL_PREFIX + TRAIN_IMAGE_FILENAME
TRAIN_IMAGE_MD5 = 'f68b3c2dcbeaaa9fbdd348bbdeb94873'

TRAIN_LABEL_FILENAME = 'train-labels-idx1-ubyte.gz'
TRAIN_LABEL_URL = URL_PREFIX + TRAIN_LABEL_FILENAME
TRAIN_LABEL_MD5 = 'd53e105ee54ea40749a09fcbcd1e9432'


class MNIST(Dataset):

    def __init__(self, data_home, mode='train', transform=None, download=True):
        super().__init__()
        assert mode.lower() in ['train', 'test'], \
            "mode should be 'train' or 'test', but got {}".format(mode)
        self.mode = mode.lower()
        self.data_home = data_home

        if mode == 'train':
            image_url = TRAIN_IMAGE_URL
            image_md5 = TRAIN_IMAGE_MD5
            image_filename = TRAIN_IMAGE_FILENAME
            label_url = TRAIN_LABEL_URL
            label_md5 = TRAIN_LABEL_MD5
            label_filename = TRAIN_LABEL_FILENAME
        else:
            image_url = TEST_IMAGE_URL
            image_md5 = TEST_IMAGE_MD5
            image_filename = TEST_IMAGE_FILENAME
            label_url = TEST_LABEL_URL
            label_md5 = TEST_LABEL_MD5
            label_filename = TEST_LABEL_FILENAME
        image_path = os.path.join(data_home, image_filename)
        self.image_path = _check_exists_and_download(
            image_path, image_url, image_md5, 'mnist', download)
        label_path = os.path.join(data_home, label_filename)
        self.label_path = _check_exists_and_download(
            label_path, label_url, label_md5, 'mnist', download)
        self.transform = transform

        self._parse_dataset()

    def _parse_dataset(self, buffer_size=100):
        self.images = []
        self.labels = []
        with gzip.GzipFile(self.image_path, 'rb') as image_file:
            img_buf = image_file.read()
            with gzip.GzipFile(self.label_path, 'rb') as label_file:
                lab_buf = label_file.read()

                step_label = 0
                offset_img = 0
                # read from Big-endian
                # get file info from magic byte
                # image file : 16B
                magic_byte_img = '>IIII'
                magic_img, image_num, rows, cols = struct.unpack_from(
                    magic_byte_img, img_buf, offset_img)
                offset_img += struct.calcsize(magic_byte_img)

                offset_lab = 0
                # label file : 8B
                magic_byte_lab = '>II'
                magic_lab, label_num = struct.unpack_from(magic_byte_lab,
                                                          lab_buf, offset_lab)
                offset_lab += struct.calcsize(magic_byte_lab)

                while True:
                    if step_label >= label_num:
                        break
                    fmt_label = '>' + str(buffer_size) + 'B'
                    labels = struct.unpack_from(fmt_label, lab_buf, offset_lab)
                    offset_lab += struct.calcsize(fmt_label)
                    step_label += buffer_size

                    fmt_images = '>' + str(buffer_size * rows * cols) + 'B'
                    images_temp = struct.unpack_from(fmt_images, img_buf,
                                                     offset_img)
                    images = np.reshape(
                        images_temp, (buffer_size, rows, cols, 1)).astype(np.uint8)
                    offset_img += struct.calcsize(fmt_images)

                    for i in range(buffer_size):
                        self.images.append(images[i, :])
                        self.labels.append(
                            np.array([labels[i]]).astype('int64'))

    def __getitem__(self, idx):
        image, label = self.images[idx], self.labels[idx]
        if self.transform is not None:
            image = self.transform(image)
        return image, label

    def __len__(self):
        return len(self.labels)
